<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Model\Map;

/**
 * 地图、经纬度相关接口类
 * Class MapController
 * @package App\Http\Controllers
 * Date : 2017-07-03
 * Time : 15:06
 * User : Yaowenzhu
 */
class MapController extends Controller
{
    // 引入trait
    use \App\lib\MyCurl;
    /**
     * 地址转经纬度
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @param type   类型 1百度 2高德
     * @param addres 地址
     * @return array
     */
    public function getLatLngByAddres(Request $request)
    {
        // 接受参数
        $type   = $request->input('type');
        $addres = $request->input('addres');
        // 假如type为空设置默认值 2高德
        $type = empty($type) ? 2 : $type;
        // 参数判断
        if(empty($addres) || !in_array($type, ['1','2'])){
            return response()->json(['code'=>'6333','msg'=>'参数错误']);
        }
        // 数据整理
        if($type == '1'){
            $data = [
                'ak'      => env('BDDT_APPKEY'),
                'city'    => '',
                'output'  => 'JSON',
                'address' => $addres
            ];
            $url = self::getBaseUrl(1);
        }else{
            $data = [
                'key'     => env('GDDT_APPKEY'),
                'city'    => '',
                'output'  => 'JSON',
                'address' => $addres
            ];
            $url = self::getBaseUrl(2);
        }

        // GET请求
        $res = self::curlGetRequest($url, $data, 5);
        $res = json_decode($res, true);
        // 高德
        if($res['status'] == '1' && $type == '2'){
            $latlng = explode(',', $res['geocodes'][0]['location']);
            $resData= ['lng'=>$latlng[0],'lat'=>$latlng[1]];
        }
        // 百度
        if($res['status'] == '0' && $type == '1'){
            $lat = (string)$res['result'][0]['location']['lat'];
            $lng = (string)$res['result'][0]['location']['lng'];
            $resData = ['lng'=>$lng,'lat'=>$lat];
        }

        if(empty($resData)){
            return response()->json(['code'=>'0033','msg'=>'解析失败']);
        }else{
            return response()->json(['code'=>'0000','msg'=>'请求成功','data'=>$resData]);
        }
    }

    /**
     * 经纬度转地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @param type 类型 1百度 2高德
     * @param lat  经纬度字符串
     * @param lng  经纬度字符串
     */
    public function getAddressByLngLat(Request $request)
    {
        // 接受参数
        $lat  = $request->input('lat');
        $lng  = $request->input('lng');
        $type = $request->input('type');
        // 假如type为空设置默认值 2高德
        $type = empty($type) ? 2 : $type;
        // 参数判断
        if(empty($lat) || empty($lng) || !in_array($type, ['1','2'])){
            return response()->json(['code'=>'6333','msg'=>'参数错误']);
        }
        // 数据整理
        if($type == '1'){
            $data = [
                'ak'          => env('BDDT_APPKEY'),
                'output'      => 'JSON',
                'location'    => $lat . ',' . $lng,
                'coord_type'  => 'bd09ll',      // bd09ll（百度经纬度坐标）、gcj02ll（国测局经纬度坐标）、wgs84ll（wgs84经纬度坐标）
                'geotable_id' => '81234'        // 与ak配合鉴权
            ];
            $url = self::getBaseUrl(3);
        }else{
            $data = [
                'key'         => env('GDDT_APPKEY'),
                'output'      => 'JSON',
                'location'    => $lng . ',' . $lat
            ];
            $url = self::getBaseUrl(4);
        }

        // GET请求
        $res = self::curlGetRequest($url, $data, 5);
        $res = json_decode($res, true);
        // 高德
        if($res['status'] == '1' && $type == '2'){
            $resData = ['addres'=>$res['regeocode']['formatted_address']];
        }
        // 百度
        if($res['status'] == '0' && $type == '1'){
            $resData = ['addres'=>$res['formatted_address']];
        }

        if(empty($resData)){
            return response()->json(['code'=>'0033','msg'=>'解析失败']);
        }else{
            return response()->json(['code'=>'0000','msg'=>'请求成功','data'=>$resData]);
        }
    }

    /**
     * 坐标系转换接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @param lat  源坐标
     * @param lng  源坐标
     * @param to   最终转换的坐标类型 可选值：gaode;bd09ll;bd09mc;
     * @param from 源坐标类型 可选值：gps;mapbar;baidu;gaode;
     * @param type 服务类型 可选值：1百度;2高德
     */
    public function getCoordinate(Request $request)
    {
        // 接受参数
        $lat  = $request->input('lat');     //源坐标
        $lng  = $request->input('lng');     //源坐标
        $from = $request->input('from');    //源坐标类型
        $type = $request->input('type');    //服务类型
        // 假如type为空设置默认值 2高德
        $type = empty($type) ? 2 : $type;
        // 参数判断
        if(empty($lat) || empty($lng) || empty($from) || !in_array($type, ['1','2'])){
            return response()->json(['code'=>'6333','msg'=>'参数错误']);
        }
        // 组合数据
        if($type == '1'){
            $data = [
                'ak'     => env('BDDT_APPKEY'),
                'from'   => self::getFromKey($from,$type),
                'coords' => $lng . ',' . $lat,
                'output' => 'json'
            ];
            $url = self::getBaseUrl(5);
        }else{
            $data = [
                'key'       => env('GDDT_APPKEY'),
                'coordsys'  => self::getFromKey($from,$type),
                'locations' => $lng . ',' . $lat,
                'output'    => 'JSON'
            ];
            $url = self::getBaseUrl(7);
        }

        // GET请求
        $res = self::curlGetRequest($url, $data, 5);
        $res = json_decode($res, true);

        // 高德
        if($res['status'] == '1' && $type == '2'){
            $cood    = explode(',',$res['locations']);
            $resData = ['lng'=>$cood[0],'lat'=>$cood[1]];
        }
        // 百度
        if($res['status'] == '0' && $type == '1'){
            $cood    = $res['result'][0];
            $resData = ['lng'=>(string)$cood['x'],'lat'=>(string)$cood['y']];
        }

        if(empty($resData)){
            return response()->json(['code'=>'0033','msg'=>'解析失败']);
        }else{
            return response()->json(['code'=>'0000','msg'=>'请求成功','data'=>$resData]);
        }
    }

    /**
     * ip定位城市接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @param ip ip地址
     * @param type 1百度 2高德
     */
    public function getCityByIP(Request $request){
        //接受参数
        $IP   = $request->input('ip');
        $type = $request->input('type');
        // 假如type为空设置默认值 2高德
        $type = empty($type) ? 2 : $type;
        if(empty($IP) || !in_array($type, ['1','2'])){
            return response()->json(['code'=>'6333','msg'=>'参数错误']);
        }

        // 组合数据
        if($type == '1'){
            $data = [
                'ip'     => $IP,
                'ak'     => env('BDDT_APPKEY'),
                'output' => 'json'
            ];
            $url = self::getBaseUrl(8);
        }else{
            $data = [
                'ip'     => $IP,
                'key'    => env('GDDT_APPKEY'),
                'output' => 'JSON'
            ];
            $url = self::getBaseUrl(6);
        }

        // GET请求
        $res = self::curlGetRequest($url, $data, 5);
        $res = json_decode($res, true);

        // 高德
        if($res['status'] == '1' && $type == '2'){
            // 数据处理
            $resData = [];
            $resData['city']     = $res['city'];
            $resData['province'] = $res['province'];
            $resData['point']    = $res['rectangle'];
        }
        // 百度
        if($res['status'] == '0' && $type == '1'){
            // 数据处理
            $resData = [];
            $resData['city']     = $res['content']['address_detail']['city'];
            $resData['province'] = $res['content']['address_detail']['province'];
            $resData['point']    = implode(',', $res['content']['point']);
        }

        if(empty($resData)){
            return response()->json(['code'=>'0033','msg'=>'解析失败']);
        }else{
            return response()->json(['code'=>'0000','msg'=>'请求成功','data'=>$resData]);
        }
    }

    /**
     * 转换请求坐标源
     * @param $from 源坐标来源
     * @param $type 地图服务类型 1百度 2高德
     * @return string
     */
    public static function getFromKey($from,$type){
        switch ($from){
            case 'gps' :
                $from = $type == '1' ? '1' : 'gps';
                break;
            case 'mapbar' :
                $from = $type == '1' ? '7' : 'mapbar';
                break;
            case 'baidu' :
                $from = $type == '1' ? '5' : 'baidu';
                break;
            case 'gaode' :
                $from = $type == '1' ? '3' : 'autonavi';
                break;
            default :
                $from = '';
                break;
        }
        return $from;
    }
}
